#Copyright (c) 2025, Alibaba Cloud and its affiliates;
#Licensed under the Apache License, Version 2.0 (the "License");
#you may not use this file except in compliance with the License.
#You may obtain a copy of the License at

#   http://www.apache.org/licenses/LICENSE-2.0

#Unless required by applicable law or agreed to in writing, software
#distributed under the License is distributed on an "AS IS" BASIS,
#WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#See the License for the specific language governing permissions and
#limitations under the License.



import json

import fce_util.libs.constants as constants
import fce_util.deploys.resource_mgr as resource
from fce_util.libs import log as loggers
from fce_util.fceres import fce_res_common


logger = loggers.g_logger.logger

def operator_check(args):
    """
    FCE Kube ray operator check entry
    """
    operator_name = args.operator_name if args.operator_name else constants.OPERATOR_NAME_PREFIX
    #kubectl_bin = "kubectl --kubeconfig={} ".format(kube_config)
    namespace = args.namespace if args.namespace else 'default'
    #cmd = "{} --namespace {}".format(cmd, namespace)
    #logger.debug('cluster_list cmd:{}'.format(cmd))
    
    if not resource.checkServiceStatus(operator_name, 'op', namespace, 6, 1):
        stdout = "kube ray operator {} check failed".format(operator_name)
        logger.error(stdout)
        fce_res_common(success = False, errcode = 'Deploy.OperatorCheckFailed', errmsg = stdout)
        return

    msg = {'Success': True}
    msg['Message'] = {
        'Msg': 'Kube ray operator check success'
    }
    print(json.dumps(msg))

def FCE_operator_check(args):
    if args.rayc == 'operator_check':
        operator_check(args)
        return
    args.this_parser.print_help()

def make(parser):
    """
    FCE Kube ray operator check entry
    """
    
    parser.add_argument( 
        '--namespace',
        dest='namespace',
        nargs = '?',
        metavar = ('NAMESPACE'),
        help='Ray Cluster Namespace',
        required=False,
    )

    parser.add_argument( 
        '--operator_name',
        dest='operator_name',
        nargs = '?',
        metavar = ('OPERATOR_NAME'),
        help='Kube Ray Operator Name',
        required=False,
    )
    
    parser.add_argument( 
        '--kube_config',
        dest='kube_config',
        nargs = '?',
        metavar = ('KUBE_CONFIG'),
        help='Kube Config File Path',
        required=False,
    )
    
    parser.set_defaults(
        func=FCE_operator_check,
        this_parser=parser
    )